#include "LinkRegion.h"

namespace Torch {
Link::Link(Region *R1,Region *R2)
{	
	m_R1 = new Region();
	m_R2 = new Region();
	m_R1=R1;
	m_R2=R2;
	m_iLabel1=R1->getLabel();
	m_iLabel2=R2->getLabel();	upDate();
	
}


void Link::upDate()
{
	int iMu1,iSigma1,iNbPixel1;
	int iMu2,iSigma2,iNbPixel2;
	
	double dSig_part1,dSig_part2,dSig;

	this->m_R1->getParameters(&iMu1,&iSigma1,&iNbPixel1);
	this->m_R2->getParameters(&iMu2,&iSigma2,&iNbPixel2);

	this->m_iNbPixel=iNbPixel1 + iNbPixel2;
	
	if(iNbPixel1 !=0 || iNbPixel2 !=0){
	this->m_iMu=(iNbPixel1 * iMu1 + iNbPixel2 * iMu2)/(iNbPixel1 + iNbPixel2);
	
	dSig_part1=(iNbPixel1*(iSigma1 + iMu1*iMu1))/(iNbPixel1+iNbPixel2);
	dSig_part2=(iNbPixel2*(iSigma2 + iMu2*iMu2))/(iNbPixel1+iNbPixel2);
	dSig=dSig_part1+dSig_part2;

	if(dSig<0)
		dSig=0;
	dSig-=(m_iMu*m_iMu);

	this->m_iSigma=dSig;
	}

}

void Link::getParameters(int *imu,int *isigma ,int *inbpixel)
{
	*imu=m_iMu;
	*isigma=m_iSigma;
	*inbpixel=m_iNbPixel;

}

void Link::setLink(int iChoix,Region *R)
{
	if(iChoix==1)
	{
		for(int i=0;i<m_R2->getNbVoisin();i++)
		{
			if(m_R2->getVoisin(i)==m_R1->getLabel())
			{
				m_R2->setVoisin(i,R->getLabel());
			}
		}
		m_R1=R;
		m_iLabel1=m_R1->getLabel();

	}
	else
	{
		for(int i=0;i<m_R1->getNbVoisin();i++)
		{
			if(m_R1->getVoisin(i)==m_R2->getLabel())
			{
				m_R1->setVoisin(i,R->getLabel());
			}
		}
		m_R2=R;
		m_iLabel2=m_R2->getLabel();
		
	}
}

void Link::supVoisin(bool bChoix,int RegionASupprimer)
{
	if(bChoix)
	{
		for(int i=0;i<m_R2->getNbVoisin();i++)
		{
			if(m_R2->getVoisin(i)==RegionASupprimer)
				m_R2->supVoisin(i);
		}
	}
	else
		for(int i=0;i<m_R1->getNbVoisin();i++)
			if(m_R1->getVoisin(i)==RegionASupprimer)
				m_R1->supVoisin(i);	

}

}
